/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package control;

import fsm.Board;
import java.util.ArrayList;
import java.util.HashMap;
import util.Constants;
import util.IOutil;
import util.LOG;
import util.Timer;

/**
 *
 * @author bomik
 */
public class Controller {
    private Board board;
    HashMap<String, Object> solveResult;
    
    // <editor-fold defaultstate="collapsed" desc="constructor zum aufbau des feldes + aufbaualgorithmus">
    public Controller(String inputfile) {
        createBoard(inputfile);
    }

    /**
     * do not use  this constructor, it's only needed for testing-purpose
     */
    public Controller() { }

    public Board getBoard() {
        return board;
    }

    public void setBoard(Board board) {
        this.board = board;
    }

    private void createBoard(String inputfile) {
        int rowLength = -1;
        int columnlength = 0;

        ArrayList<Short> list = new ArrayList<Short>();
        IOutil.startReading();
        while (IOutil.getReader().hasNextLine()) {
            String line = IOutil.getReader().nextLine().trim();
            LOG.debug("aktuelle Linie[" + line + "]");
            if (line.charAt(line.length() - 1) != ';') {
                throw new IllegalArgumentException("inputfile broken, lines has to end with an ';'\t" + line.charAt(line.length() - 1));

            }
            line = line.substring(0, line.length() - 1);//remove ';' at endline
            String[] items = line.split(",");
            //check if column-size is correct
            if (rowLength != -1 && rowLength != items.length) {
                throw new IllegalArgumentException("inputfile broken, Spielfeld ausgefranst");

            }
            rowLength = items.length;
            ++columnlength;
            for (int i = 0; i < items.length; i++) {
                try {
                    list.add((short) Integer.parseInt(items[i]));
                } catch (RuntimeException ex) {
                    throw new IllegalArgumentException("ungueltiger Eintrag " + items[i] + " @ " + (columnlength + 1) + ".Zeile, "
                            + (i + 1) + ". Spalte", ex.fillInStackTrace());
                }
            }
            board = new Board(rowLength, columnlength);
            int y = columnlength - 1;
            for (int i = 0; i < list.size(); i++) {
                int x = i % rowLength;
                board.setField(x, y, list.get(i));
                if (x == (rowLength - 1)) {
                    y--;

                }
            }
        }
        IOutil.stopReading();
    }// </editor-fold>
    
    public void solve(){
        Timer.start();
        SolveAlgorithmBruteForce alg = new SolveAlgorithmBruteForce();
        Solution result = alg.solve(board);
        board = result.board;
        Timer.stop();
    }
}
